#include "sloverevisionnotfounddialog.h"
#include "ui_sloverevisionnotfounddialog.h"

#include <QDir>
#include <QPushButton>

SloveRevisionNotFoundDialog::SloveRevisionNotFoundDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::SloveRevisionNotFoundDialog)
{
    ui->setupUi(this);

    QPushButton *btn = ui->buttonBox->button(QDialogButtonBox::Ok);
    if (btn) btn->setEnabled(false);

    m_process.setProcessChannelMode(QProcess::MergedChannels);

    connect(&m_process, qOverload<int>(&QProcess::finished), this, [this](int exitCode)
    {
        if (exitCode == 0)
        {
            emit fetched();
            setWindowTitle("repo 检出完成: " + m_path);
        } else {
            setWindowTitle("repo 检出异常: " + m_process.errorString());
        }

        if (ui) {
            QPushButton *btn = ui->buttonBox->button(QDialogButtonBox::Ok);
            if (btn) btn->setEnabled(true);
        }
    });

    connect(&m_process, &QProcess::readyRead, this, [this]()
    {
        QString output;
        output = m_process.readAll();
        ui->fetch_revision_content->appendPlainText(output);
    });

    m_procinfo_timer.setInterval(1000);
    m_procinfo.getLinuxNetworkDownload(); // first clean speed;
    connect(&m_procinfo_timer, &QTimer::timeout, this, [this](){
        double downSpeed = 0;
        ProcInfoUtils::SpeedRateUnit unit;

        unit = ProcInfoUtils::SpeedRateByte;
        long download = m_procinfo.getLinuxNetworkDownload();
        QString downUnit = m_procinfo.autoRateUnits(download, unit, downSpeed);
        //↓:
        QString down_speed_text =  QString("↓:%1").arg(downSpeed, 0, 'f', 2, QLatin1Char(' ')) + downUnit;
        ui->label->setText(down_speed_text);
    });
    m_procinfo_timer.start();
}

SloveRevisionNotFoundDialog::~SloveRevisionNotFoundDialog()
{
    delete ui;
    ui = nullptr;
}

void SloveRevisionNotFoundDialog::setWorkdir(const QString &newWorkdir)
{
    m_workdir = newWorkdir;
}

void SloveRevisionNotFoundDialog::setPath(const QString &newPath)
{
    m_path = newPath;
}

void SloveRevisionNotFoundDialog::setRemote(const QString &newRemote)
{
    m_remote = newRemote;
}

void SloveRevisionNotFoundDialog::setRevision(const QString &newRevision)
{
    m_revision = newRevision;
}

void SloveRevisionNotFoundDialog::start()
{
    QString once_info("-- git fetch %1 %2 -- \n");
    QStringList arguments("fetch");
    {
        arguments << m_remote << m_revision;
        once_info = once_info.arg(m_remote).arg(m_revision);
    }
    ui->fetch_revision_content->setPlainText(once_info);
    m_process.setWorkingDirectory(m_workdir + QDir::separator() + m_path);
    m_process.setProgram("git");
    m_process.setArguments(arguments);
    m_process.start();
}
